#!/usr/bin/env python2.5
# -*- coding: UTF-8 -*- 
# what is this ? Cookie: dev_appserver_login="nickmilon@gmail.com:False:119222404092061841222"; django_language=en 
  
### import wsgiref.util         #usefull utils no overhead since  run_wsgi_app imports those too  

from nmpacks.milonpy  import NMserver
run_wsgi_app =NMserver.webapp.util.run_wsgi_app
webapp=NMserver.webapp
datetime=NMserver.datetime
html=NMserver.html
db=NMserver.db  
import models  
country_list=models.country_list
AppSetingsDic=models.AppSetingsDic
from nmpacks.milonpy import NMutl as utl
from nmpacks.milonpy import NMtbl as tbl  
#import  nmpacks.milonpy.NMutl as utl 
re=db.re 

tbl.GLNMdictSkipValidation=True
instance=0
tmplHead=html.NMtmpl('tmpls/head.html')
#tmpl_row=html.NMtmpl('tmpls/row_cntr.html')
geotb=0 
Gl_StatisticsDictCashe=None
memcache=NMserver.memcache  
def GoogleDocumentClean(htmlstr):
    htmlstr=re.sub("<html>",'<div class="nm-gdoc-div">',htmlstr)
    htmlstr=re.sub("</html>", "</div>",htmlstr)
    htmlstr=re.sub("</*?head>","",htmlstr)
    htmlstr=re.sub("<body","<div",htmlstr) 
    htmlstr=re.sub("</body>","</div>",htmlstr) 
    htmlstr=re.sub("<title>.*?</title>","",htmlstr) 
    return htmlstr
class dictCashe(dict):  
    def __init__(self,rowKey, dictFun = lambda : ({'aa':11}), namespace='ns1', title='' ):
        """dictFun a dictionaryreturning function so that we evaluate it if not found """
        dict.__init__(self)
        self.rowKey=rowKey
        self.namespace=namespace 
        self.title=title 
        self.hit=0  # 1= found in memcache 2 in datastore
        dictArg= memcache.get(rowKey, namespace=namespace) 
        if dictArg is None:
            dictArg = AppSetingsDic.get(rowKey)
            if dictArg is None: 
                dictArg=dictFun() 
                AppSetingsDic.set(self.rowKey, dictArg, namespace=self.namespace, tilte=self.title)  
            else: 
                self.hit=2
                self.title =  dictArg.title
                dictArg=dictArg.dicVal    
            memcache.set(rowKey,  repr(dictArg),  namespace=self.namespace) 
        else: 
            self.hit=1
            dictArg=eval(dictArg)  
        self.update(dictArg)
    def setVal(self, key, val): 
        memcache.set(self.rowKey, repr(self),  namespace=self.namespace)
        AppSetingsDic.set(self.rowKey, self ,  namespace=self.namespace, tilte=self.title )     
    def __setitem__(self,key,val):
        dict.__setitem__(self,key, val)
        self.setVal (key, val)
    def __delitem__(self,key):
        dict.__delitem__(self,key)
    def deleteFromMemcashe(self):
        memcache.delete(self.rowKey, namespace=self.namespace) 
#-------------------------------------------------------------------------------------------------------------------------
def getStatisticsDictCashe():
    global Gl_StatisticsDictCashe
    Gl_StatisticsDictCashe=None
    if Gl_StatisticsDictCashe is None: 
        dictFun=lambda : ( {'tagGroups':"All,Popular,Latest,Geography,Demographics,Economy,Government,Organizations".split(',')} )
        Gl_StatisticsDictCashe= dictCashe( 'StatisticsDictCashe', dictFun , 'stats', 'Statistics Groups') 
    return Gl_StatisticsDictCashe      
def initInstance(): 
    global instance
    global geotb;  
    global stdMenu  
    #memcache.flush_all()
    if instance==0:   
        instance=datetime.datetime.now()  
        NMserver.logging.info("initInstance:" + str(instance))
        geotb=tbl.NMtableGeo() 
        geotb.CSVload('res/geodump.csv', 3, skipValidations=True, colkey='&nbsp;')  
        #geotb = memcache.get('geotb') 
        #if geotb is None:
            #geotb=tbl.NMtableGeo() 
            #geotb.CSVload('res/geodump.csv', 3, skipValidations=True, colkey='&nbsp;') 
            #memcache.flush_all() 
            #memcache.add("geotb", geotb, 6000)
            #logging.info("cache fail:" + 'geotb')    
#def rowCont(title, Contents, id=False, level=2) :
#    Cont = html.div( )  
#    if  id : Cont.attrSetId(id)
#    Cont.attrSetClass("nm-lev-" + "%02d" % level)
#    Cont.attrAppendCnt(level, 'nmlv-') 
#    ContDivH1_6=html.div(html.h1_6(title,level))
#    ContDivH1_6.attrSetClass('nm-c-lev-'+ "%02d" % level) 
#    Cont.insertContents(ContDivH1_6)
#    Cont.insertContents(Contents)
#    Cont.insertContents( html.div('', 'class=\"nm-dummy-last\"'))
#    return Cont                        
def StdMenu(lng , inclCountryList=True):
    #print "xxxxxxxxx" *10, inclCountryList, inclIntOrg 
    tmp= html.ul( [html.a('Home','', '/geo/'+lng+'/home.html' ), html.a('Help','',  '/geo/'+lng+'/help.html' ) ] ,  'class=\"nm-hnav\"' ) 
    if inclCountryList: tmp.insertContents(html.ul.li(html.a( 'Country Lists','',  '/geo/'+lng+'/countries-list-menu/All.html') ) )  
    tmp.insertContents(  html.ul.li('&nbsp', 'class=\"nm-hnav-sep\"') )
    tmp.attrSetClass('nm-hnav') 
    return tmp

def ReqHandlDebug(rqhandl):
    def printdir(item):
        print [type(item),  '_'*50]
        for it in dir(item):
            #if isinstance(it, basestring)
            print [it]
    print 'Start ------------'
    printdir(rqhandl)   
    printdir(rqhandl.request)  
    print['host ,host_url',  rqhandl.request.host, rqhandl.request.host_url]
    print['urlvars', rqhandl.request.urlvars]
    print rqhandl.request.__dict__ 
    print 'environ'
    for key in rqhandl.request.environ.keys():
        print [key, rqhandl.request.environ[key]]  
        print '\n'
    print 'End ------------' 
class home_Sitemap(NMserver.ReqHadlerNM):
    useCashe = 7
    isStaticContent=False
    def Responce_ContentType(self) : 
        return "application/xml"    
    def getC(self):
        initInstance()
        sitemap=html.urlset()
        l='en'    
        #cdt=datetime.datetime.strftime(datetime.datetime.utcnow(),utl.HTTP_DATE_FMT) #now.strftime('%a, %d %b %Y %H:%M:%S GMT')
        #cdt=datetime.datetime.isoformat(datetime.datetime.utcnow())
        cdt=re.sub( "\..*","+00:00",datetime.datetime.isoformat(datetime.datetime.utcnow()))
        uriBase='http://www.geognos.com/'
        sitemap.addUrl(uriBase ,cdt, 'monthly','1')
        uriBase +='geo/'+ l + '/'
        uriRegions=uriBase+'region/' 
        uriCC=uriBase+'cc/'
        uriListingsMnu=uriBase +"countries-list-menu/"
        uriListings=uriBase +"countries-list/"
        tmpFrmtstr=u"%s%s.html"
        regions=list(set([geotb[k]['&nbsp;']['region'][l] for k in geotb.keys()])) 
        sitemap.addUrl(uriBase + 'home.html',cdt, 'monthly','0.9') 
        for tmp in ('tos', 'privacy', 'help' , "world-countries-API"):sitemap.addUrl(tmpFrmtstr %(uriBase, tmp),cdt, 'monthly','0.1')
        for tmp in regions:     sitemap.addUrl( tmpFrmtstr %(uriRegions, tmp.replace(' ', '-')), lastmod=cdt, changefreq='monthly', priority='0.5' )   
        for k in geotb.keys():  sitemap.addUrl(tmpFrmtstr %(uriCC, k),cdt, 'weekly','0.8' ) 
        StatisticsDictCashe=getStatisticsDictCashe() 
        for tag in StatisticsDictCashe.get('tagGroups', []):sitemap.addUrl(tmpFrmtstr %(uriListingsMnu,tag),cdt, 'weekly','0.5' )  
        for item in country_list.getAll(): 
            modified=cdt=re.sub( "\..*","+00:00",datetime.datetime.isoformat(item.modified))
            sitemap.addUrl(tmpFrmtstr %(uriListings,item.key().id_or_name()),modified, 'monthly','0.6' )                                             
        return sitemap()
class feeds(NMserver.ReqHadlerNM):
    useCashe = 7
    isStaticContent=True
    def cacheKey(self):             return "%s?%s" %(self.request.path_info, self.request.query_string)
    def Responce_ContentType(self): return "application/rss+xml" #application/rdf+xml,  application/atom+xml
    def getC(self, lang, tp,arg,  fname):
        initInstance()
        pubDate='Thu, 01 Jul 2010 00:00:00 +0000' 
        uriBase="http://www.geognos.com/" 
        uriCanonical=uriBase+self.request.environ['PATH_INFO']
        if tp == 'countries':
            rss=html.rss('geognos.com', uriCanonical,'World Countries Atlas with Information about all countries', isMRSS=True, isDC=True, isGeo=True)
            rssC=rss._channel
            rssC.insertContents(rssC.image(uriBase+"media/img/logo_180X63.png" , 'geognos.com', uriBase+'rss'))
            rssC.insertContents(rssC.language(lang))
            rssC.insertContents(rssC.pubDate(pubDate))
            rssC.insertContents(rssC.webMaster('webmaster@geognos.com (Nick Milon)'))    
            uriCC=uriBase+'geo/'+lang+'/cc/' 
            uriFlag=uriBase+"cds/en/flag/"
            tmpFrmtstr=u"%s%s.html" 
            """
            NMRow({' ': NMdict({'country': NMlngS({'en': 'Greece'}), 'region': NMlngS({'en': u'Europe'}), 
            'flgof': 84, 'latLng': ['39 00 N, 22 00 E', '39.00;22.00', '37 59 N, 23 44 E', '37.59;23.44'],
            'ccs': ['GR', '300', 'GRC', 'GR', 'gr', 'Greece']}), 
            '_info_': NMdict({'K': 'gr', 'TMc': datetime.datetime(2010, 6, 26, 23, 41, 27, 256306), 'RN': 4})})
            
            <georss:box>42.943 -71.032 43.039 -69.856</georss:box> 
            """  
            #rowKeys=geotb.keys()   
             
            Qccs=self.request.get('ccs', False)  
            if Qccs:
                rowKeys=geotb.keys()
                Qccs=Qccs.split(',') 
                rowKeys=[ it  for it in Qccs if it in rowKeys]
            else:
                rowKeys=[k[1] for k in geotb.getCntrCCSorted(lang)]     
                Qregion=self.request.get('region', False)   
                if Qregion:rowKeys=[ k  for k in rowKeys if geotb[k]['&nbsp;']['region']['en'] == Qregion]  
            #rowKeys.sort() 
            for k in rowKeys: #geotb.getCntrCCSorted(lang):  
                uriFlagCurrent=uriFlag+k+"/160X80/"
                #uriFlagCurrent=uriBase+"/media/img/logo_180X63.png"
                countryRecord= geotb[k]['&nbsp;']
                countryName=countryRecord['country'][lang]
                description= description=countryName + ': Map, Photos, Country, Background, Geography, Demographics, Government, Economy, Communications, Transportation'
                item=rssC.addItem(title=countryName, link=tmpFrmtstr %(uriCC, k), description= description, pubDate=pubDate,  guid=None) 
                item.insertContents(item.enclosure(url=uriFlagCurrent,length='5000', type='image/png')  )
                countryCenter=countryRecord['latLng'][1].replace(';', ' ') 
                item.insertContents(item.georss_point( countryCenter) )
                media=item.insertContents(item.media_content(url=uriFlagCurrent,  type='image/png',  medium="image", height="80", width="160") )
                media.setFields(countryName, 'Information about '+ countryName )
                media.insertContents(item.media_thumbnail(url=uriFlagCurrent, height="80", width="160") )
                #item.insertContents(item.category('Geography'))    
            #print 'xxxx ' * 10,  str(geotb['gr'])        
            #return 'xxxx ' * 10 + str(geotb['gr'])  
            return rss()       
        else: return u'not implemented'    
class home_NotesRQH(NMserver.ReqHadlerNM): 
    cookieName_Path=['geognosgeo','/geo/'] 
    useCashe = 4
    tmplHeader  =  html.NMtmpl('tmpls/header.html')  
    tmplFooter  =  html.incl  ('tmpls/tmpl_footer.html')
    #tmplFooter =  html.NMtmpl  ('tmpls/tmpl_footer.html')   
    tmplInfo =     html.NMtmpl('tmpls/tmpl_info.html') 
  
    def getC(self, lng, arg):  
        self.content_language=lng
        ytml=html.y_html(html.y_html.width.doc3,html.y_html.sidebar.t2, html.incl('tmpls/etc/ga_async.js'))  
        nm_divRow=html.rowCont('',[html.div( html.div('', 'id=\"nm_divmsc_contents\"'))] ,"nm_divRow",3)  
        #nm_divRow_cont=html.rowCont("",  nm_divRow, "nm_row_container", 2)    
        argDescription=''
        argKeyWords=''
        urlcanonical=self.request.environ['PATH_INFO'] 
        ##nm_sidebar_l1_cont = rowCont ("Flag", html.div( html.div('', 'class=\"nm-animpos\"'), 'class=\"nm-cont-lh0\"' ) , "nm_sidebar_l1_cont", 2)  
        ##ytml.mnuConts.insertContents(  html.div( html.div('', 'class=\"nm-animpos\"')))
        ##ytml.doc_bd_sidebar.insertContents(html.div(nm_sidebar_l1_cont,'id=\"nm_sidebar_l1\" class=\"nm-lev-02\"' ))  
        mnuConts = StdMenu(lng) 
        if  arg=='home' or arg.startswith('region'): 
            initInstance()
            regions=list(set([geotb[k]['&nbsp;']['region'][lng] for k in geotb.keys()]))
            regions.sort()   
            if arg=='home': 
                curRegion  = False 
                argTrans='World Countries'
                urlcanonical='/geo/en/home.html'
                argDescription=self.tmplInfo.render({'req':arg, 'lng':lng}).strip()
                argDescriptionH3=html.h3(argDescription.replace(',', ',<br>'), 'id=\"nm_description"')
                argKeyWords=re.sub('\swith\s|\sand\s|\son\s|\sabout\s', ',', argDescription).replace('  ',' ')
                #ytml.html_head.insertContents(html.incl  ('tmpls/head_extraroot.html'))
            else: 
                arg= arg.split('/')
                curRegion=arg[1].replace('-', ' ')
                arg=arg[0]    
                argTrans= curRegion 
                argDescription=[geotb[k]['&nbsp;']['country'][lng] for k in geotb.keys() if geotb[k]['&nbsp;']['region']['en']  == curRegion]
                argDescription.insert(0, curRegion)   #!should be in curLng
                argDescription=','.join(argDescription) 
                argKeyWords=argDescription
                argDescriptionH3=''
           
            argfrmOptions=html.dummytag(geotb.getHtmlKeyOptions(lng, False))
            nm_flagcontents= html.div('', 'id=\"nm_flagcontents\"')
            nm_divRowcontents= html.div(nm_flagcontents, 'id=\"nm_divrowcontents"') 
            nm_divRow=html.rowCont("Countries - Flags", nm_divRowcontents , "", 2)  
             
            for k in geotb.getCntrCCSorted(lng): 
                if arg=='home' or geotb[k[1]]['&nbsp;']['region']['en']  == curRegion:   
                    curFlg=html.p( '', 'class=\"nm-flg\"') 
                    ##print   geotb[k[1]]['&nbsp;']['flgof']
                    curFlg.attrSetStyle("background-position: -" + str((geotb[k[1]]['&nbsp;']['flgof']) *80) + "px")
                    curFlg.attrSetTitle(k[0]) 
                    tmp=html.mformatGeoAbr(geotb[k[1]]['&nbsp;']['latLng'][1], k[0]) 
                    tmp=html.a(tmp, '', '/geo/' + lng +'/cc/'+ k[1]+'.html') 
                    nm_flagcontents.insertContents(html.span([curFlg,tmp], 'class=\"nm-flgraper\"')) 
            nm_flagcontents.insertContents( html.div('', 'class=\"nm-dummy-last\"'))    
            #tmp=html.h3(argDescription.replace(',', ',<br>'), 'id=\"nm_description"')
            tmpimg=html.img(src="/media/img/logo_180X63.png" , alt='geognos Logo' , title='geognos.com', height=False, width=False)
            nm_sidebar_l1_cont = html.rowCont ("&nbsp;", html.div( [tmpimg, argDescriptionH3], 'class=\"nm-home-lh0\"' ) , "nm_sidebar_l1_cont", 2)  
            ytml.doc_bd_sidebar.insertContents(html.div(nm_sidebar_l1_cont,'id=\"nm_sidebar_l1\" class=\"nm-lev-02\"' ))  
            # regions= [html.a(vl, attributes='', href='/geo/'+lng+'/region/'+vl.replace(' ', ' ') +'.html') for vl in regions ]
            nm_sidebar_l2_cont = html.rowCont ("", html.p(' Select a region from the menu or visit a country by clicking on its flag or selecting from the drop box located at the top right of this page.' ,'class=\"nm-home-lh2\"' ) , "nm_sidebar_l2_cont", 2) 
            ytml.doc_bd_sidebar.insertContents(html.div(nm_sidebar_l2_cont,'id=\"nm_sidebar_l2\" class=\"nm-lev-02\"' ))  
            
        elif arg=='help':
            argTrans='Help'
            argDescription=argTrans
            argKeyWords=argTrans
            argfrmOptions=''
            #class="nm-info"
            nm_divRowcontents= html.div(html.div(self.tmplInfo.render({'req':arg, 'lng':lng}), 'class=\"nm-info\"'), 'id=\"nm_divrowcontents\"')
            nm_divRow=html.rowCont("&nbsp;", nm_divRowcontents , "", 2)   
        elif arg=='privacy':
            argTrans='Privacy Policy'
            argDescription=argTrans
            argKeyWords=argTrans
            argfrmOptions=''
            nm_divRowcontents= html.div(html.div(self.tmplInfo.render({'req':arg, 'lng':lng}),  'class=\"nm-info\"'), 'id=\"nm_divrowcontents\"')
            nm_divRow=html.rowCont("&nbsp;", nm_divRowcontents , "", 2)       
        elif arg=='tos':
            argTrans='Terms Of Service'
            argDescription=argTrans
            argKeyWords=argTrans
            argfrmOptions=''
            nm_divRowcontents= html.div(html.div(self.tmplInfo.render({'req':arg, 'lng':lng}), 'class=\"nm-info\"'), 'id=\"nm_divrowcontents"')
            nm_divRow=html.rowCont("&nbsp;", nm_divRowcontents , "", 2)    
        elif arg=="world-countries-API": 
            argTrans='World Countries API'
            argDescription="World Countries Information and ip geocoding  RESTful Web services API"
            argKeyWords="World,Countries, Information,geocoding,API"
            argfrmOptions='' 
            contFromGD=utl.fl_read('tmpls/worldcountriesAPI.html')
            contFromGD=GoogleDocumentClean(contFromGD)  
            nm_divRowcontents= html.div(contFromGD, 'class=\"nm-gdoc\"')
            nm_divRowcontents.insertContents("""<br><iframe src="http://spreadsheets0.google.com/embeddedform?formkey=dERPX3FjVndOQXd6d05iRFZBOEZxV3c6MQ" 
                          width="100%" height="971" frameborder="2" marginheight="10" marginwidth="10">Loading...</iframe>""")
            nm_divRow=html.rowCont("&nbsp;", nm_divRowcontents , "", 2) 
           
            #ytml.doc_bd_cnts.insertContents(nm_divRow) 
        
        ytml.doc_bd_cnts.insertContents(nm_divRow) 
        #site = 'geognos ' 
        self.tmplD.update({'language':lng,'urlcanonical':urlcanonical, 'urlbase': self.request.host_url,  'description':  argDescription ,'inclmap':False,'title':argTrans, 'keywords':argKeyWords, 'lang':lng, 'frmAction': "/geo/switch/", 'frm2Action':"/geo/switch/" , 'frmOptions':argfrmOptions, 'page_css':'yuinm'} )     
        #'canonical':self.request.environ['PATH_INFO'] 
        ytml.setdefaults(argTrans, self.tmplFooter ,mnuConts, False,  'nm-'+ arg+' nm-genuse')     
        ytml.cntr_panel.insertContents(html.incl(self.tmplHeader.render(self.tmplD)))  
        ytml.html_head.insertContents(html.incl (tmplHead.render(self.tmplD)))  
        if arg=='home': ytml.html_head.insertContents(html.incl  ('tmpls/head_extraroot.html')) 
    ##      if arg=='home':
    ##         ytml.mnuConts.insertContents([html.a('Help','class=\"nm_cont_gl\"',  '/geo/'+lng+'/help.html' )] )
    ##      elif arg=='help':
    ##         ytml.mnuConts.insertContents([html.a('Home','class=\"nm_cont_gl\"', '/geo/'+lng+'/home.html' ) ] )  
    ##      else:   
        #ytml.mnuConts.insertContents([html.a('Home','class=\"nm_cont_gl\"', '/geo/'+lng+'/home.html' )] )   
    ##         ytml.mnuConts.insertContents([html.a('Home','class=\"nm_cont_gl\"', '/geo/'+lng+'/home.html' ), html.a('Help','class=\"nm_cont_gl\"',  '/geo/'+lng+'/help.html' ) ])   
        
        if  arg=='home' or arg=='region': 
            mnuConts.insertContents ( [ html.ul.li(html.a(r, '', '/geo/en/region/' + r.replace(' ', '-') +'.html') )    for r in regions] )
            #mnuConts.insertContents (html.ul.li( [html.a(r, '', '/geo/en/region/' + r.replace(' ', '-') +'.html') for r in regions]  )) 
            ytml.html_head.insertContents(html.script ('', "/media/js/nmjsfwk00.js"))  
            ytml.html_head.insertContents(html.incl('tmpls/etc/frontpages.js')) 
        ytml.html_head.insertContents(html.incl('tmpls/etc/applcommon.js')) 
        return ytml()
class countryRQH(NMserver.ReqHadlerNM): 
    useCashe = 4
    cookieName_Path=['geognosgeo','/geo/']  
    tmplHeader =     html.NMtmpl('tmpls/header.html')  
    tmplFooter  =   html.incl('tmpls/tmpl_footer_Countries.html')
    ##rootCol = geotb.Columns.keys()[0].root() 
    viscolsPie = ['LandUse',  'Religions', 'LegislBranch', 'GDPDistrib', 'LabForDistr', 'ExportPartners' , 'ImportPartners',  'Budget'] 
    viscolsBar = ['HouseIncome']
  
    def getC(self, lng, cntr):   
        initInstance() 
        self.content_language=lng 
        lng='en' #! Temporary till we have  translations   
        def setcontents():  
            def genCont(cnt=0, sck=None, startItem=None):  
                def prepContainer(column):
                    container= html.div()
                    container.attrSetClass('%s %s%02d' % ('nm-row','nm-lev-', column.level+1))
                    container.attrAppendCnt(cnt, 'nmlv-')  
                    return container 
                def prepVal(column): 
                    def prepTbl(Val): 
                        contDiv.attrAppendClass('nm-tbl')
                        if Val.body is None:contDiv.attrAppendClass('nm-empty')
                        Val=html.div(Val)
                        Val.attrSetId('nm_cont_' + colobjShortNameMod)  
                        Val.attrAppendClass('nm-dv-cont')  
                        return Val
                    colobj = geotb.Columns[column]
                    colobjShortName = colobj.getShortName() 
                    colobjShortNameMod=colobjShortName.replace('-', '')
                    contDiv = html.div() 
                    contDiv.attrSetId(colobjShortNameMod)    
                    contDiv.attrSetClass('%s %s%02d ' %('nm-cont','nm-c-lev-', column.level+1))
                    contDiv.attrAppendCnt(cnt) 
                    caption = "Map :" if  column.level== 0 else  colobj.GetTitle()[lng]  + ' : ' 
                    ContentsLst.append(column) 
                    Keywords.append([ colobj.GetTitle()[lng], column.level])
                    #h1_6=html.tag(caption, 'class=\"nm-hd\"',  name='h'+str(min(6, max(2, column.level+1))))
                    aName=html.a(caption)
                    aName.attrSetName(caption[:-3])
                    h1_6=html.h1_6(aName,max(2, column.level+1)) 
                    contDiv.insertContents(h1_6)   
                    if colobjShortName.startswith('--'): 
                        Val=geotb.getHtmlTbl(cntr,children, lng) 
                        Val=prepTbl(Val) 
                        contDiv.attrAppendClass('nm-multy')  
                    else:   
                        Val=geotb.getHtml(cntr, column, lng, None, self.request.environ['PATH_INFO']) if  column.level !=0 else html._nbsp  
                        ##print [cntr, column, lng, None, self.request.environ['PATH_INFO']   ] 
                        if isinstance(Val, html.table):
                            Val=prepTbl(Val)
                            if colobjShortName in self.viscolsPie or colobjShortName in self.viscolsBar: 
                                visDiv = html.div('', 'class=\"div_nm_vis\"') 
                                visDivId = 'nm_vis_' + colobjShortNameMod
                                visDiv.attrSetId(visDivId) 
                                Val.insertContents(visDiv) 
                                vlGV = geotb.getGVTable(cntr, column, lng)   
                                chartType= 'ColumnChart' if colobjShortName in self.viscolsBar else 'PieChart'
                                colEven = int(column[7:9] ) %  2 == 0  
                                scriptGV.insertVisualization(visDivId,  chartType, '',vlGV, bgncolor= '#61a7f2' if colEven else '#5590D2', lgntxtcol='white')  
                        elif isinstance(Val, (html.ul, html.ol)):
                            Val=html.div(Val)
                            Val.attrAppendClass('nm-dv-cont')
                    if Val != html._nbsp:   
                        if isinstance(Val, basestring): 
                            if len(Val) < 50:contDiv.attrAppendClass('nm-short')
                            Val = html.p(Val) 
                        contDiv.insertContents(Val)
                    else:
                        if not colobjShortName.startswith('-'):contDiv.attrAppendClass('nm-empty')  
                    return contDiv  
                if sck is None: sck=sorted( [x for x in geotb.Columns.keys() if (not x.endswith('_') and not x.endswith('dd') )] )    
                if startItem is None:startItem=sck[0]     
                children=startItem.children(sck)     
                containerVal=prepVal(startItem)  
                if len(children) > -1:  # 0:          ! if`it works bgale to if
                    ChapterContainer = prepContainer(startItem)  
                    ChapterContainer.insertContents(containerVal)  
                    ChapterContainer.attrAppendClass(containerVal.attrGetId())
                    if not containerVal.attrIsOfClass('nm-multy'):
                        cnt=1
                        for child in children: 
                            genC=genCont(cnt, sck, child)
                            if not genC.attrIsOfClass('nm-empty'):
                                cnt+=1  
                                ChapterContainer.insertContents(genC)  
                        ChapterContainer.insertContents(html.div('', 'class=\"nm-dummy-last\"'))
                        return ChapterContainer
                else:
                    return containerVal 
                ChapterContainer.insertContents(html.div('', 'class=\"nm-dummy-last\"'))
                return ChapterContainer  
            return genCont()   
        rt= geotb.CSVload('res/geodump.csv', 2, skipValidations=True, rowkey=cntr)  
        if rt is None:return self.raiseErrCode400('No such Country Code:'+ cntr )  
        CurCountryInLng= geotb[cntr]['&nbsp;']['country'][lng]   
        CurRegionInLng= geotb[cntr]['&nbsp;']['region'][lng]   
        ytml=html.y_html(html.y_html.width.doc3, html.y_html.sidebar.t1, html.incl('tmpls/etc/ga_async.js'))  
        ytml.setdefaults(CurCountryInLng , self.tmplFooter , docclass='nm-countryRQH') 
        self.tmplD.update({'language':lng,'inclmap':True, 'lang':lng, 'title': CurCountryInLng,'page_css':'yuinm',  'frmAction': "/geo/switch/", 'frm2Action':"/geo/switch/", 'frmOptions':html.dummytag(geotb.getHtmlKeyOptions(lng, cntr)) })
         
        ytml.cntr_panel.insertContents(html.incl(self.tmplHeader.render(self.tmplD)))  
         
        ytml.html_head.insertContents(html.noscript(html.style('.nm-jsonly{display:none ! important ;}  #Country {display: none;}', 'type="text/css"' ))) 
        ytml.html_head.insertContents(html.scriptGjsapi()) 
        ytml.html_head.insertContents(html.scriptGMapsV3())
        
        scriptGV = html.scriptGV()
        ytml.html_head.insertContents(scriptGV)  
        #._strGet(self[key][col],  lng)
        cntrNames= geotb._strGet(geotb[cntr]['&nbsp;.04.01'], lng) 
        
        cntrCodes = geotb[cntr]['&nbsp;']['ccs']   
        #url="%s%s%s%s" %(self.request.host_url, "/api/en/countries/flag/", cntr.upper(), ".png")
        nm_sidebar_l1_cont = html.rowCont ("Flag", html.div(html.img(src="/api/en/countries/flag/"+cntr.upper()+".png" , alt='Flag of '+CurCountryInLng , title='Flag of '+CurCountryInLng, height=False, width=False), 'class=\"nm-cont-lh0\"' ) , "nm_sidebar_l1_cont", 2) 
        #nm_sidebar_l1_cont = html.rowCont ("Flag", html.div(html.img(src="/cds/en/flag/"+cntr.lower()+"/160X80/" , alt='Flag of '+CurCountryInLng , title='Flag of '+CurCountryInLng, height=False, width=False), 'class=\"nm-cont-lh0\"' ) , "nm_sidebar_l1_cont", 2) 
         
        ytml.doc_bd_sidebar.insertContents(html.div(nm_sidebar_l1_cont,'id=\"nm_sidebar_l1\" class=\"nm-lev-02\"' ))     
        
        ContentsLst=[] 
          
        Keywords=[[CurRegionInLng,  1], [CurCountryInLng,  1]]  
        Keywords.extend([[it, 2] for it in cntrNames if it !='']) 
        Keywords.extend([[it, 2] for it in cntrCodes]) 
        Keywords.extend([[it, 1] for it in ['Map', 'Photos']])   
        nm_divHidden=html.rowCont('',[html.div( html.div('', 'id=\"nm_divHidden_contents\"'))] ,"nm_divHidden",3)  
        nm_divHidden_cont=html.rowCont("",  nm_divHidden, "nm_divHidden_container", 2)  
        nm_divHidden_cont[0].insertContents(html.div(html.span('X','id=\"nm_divHidden_cp\"'), 'id=\"nm_divHidden_cp_div\"' ) , 1) 
        contents=setcontents()
        contents.insertContents(nm_divHidden_cont, 0) 
        ytml.MainRow[0].insertContents(contents)   
        self.tmplD['keywords'] =  ", ".join([it[0] for it in Keywords if it[1] < 3 ]) 
        self.tmplD['description'] =  ", ".join([it[0] for it in Keywords if    it[1] < 2]) 
        self.tmplD['urlcanonical']=self.request.environ['PATH_INFO']  
        self.tmplD['urlbase'] = self.request.host_url            
        #return str(ContentsLst)
        
        ContentsLst=geotb.getColTreeFun('&nbsp;',lambda y: y in ContentsLst, lambda y: geotb.Columns[y].GetTitle()[lng])  
        
        ############
        #ContentsLst=ContentsLst[1:]
        #return str(ContentsLst)
        ##############
       
        ContentsLst[0]=CurCountryInLng   
        utl.lst_removeEmpty   (ContentsLst) 
        utl.lst_remove1Level0 (ContentsLst)
        tmp=ContentsLst[1][1:]
        tmp.insert(0, ContentsLst[1][0])
        #return str(tmp)
        #return   html.itemToUlLi(tmp[1],lambda x: html.a(x,'', "#"+x ) )()
        #  r=html.itemToUlLi(l[1][2],lambda x: html.a(x,'', "#"+x ) )  
        #html.lst_toTagBookMark(ContentsLst) # , baseUri=  self.request.environ['HTTP_HOST']    + self.request.environ['PATH_INFO'] )  
        mnuConts = StdMenu(lng)
        #mnuConts.insertContents(html.itemToUlLi(tmp[1],lambda x: html.a(x,'', "#"+x ) ) )
        #r1=html.lstToUL(tmp[1],lambda x: html.a(x,'', "#"+x ))
        #print r1() 
        #mnuConts.insertContents(r1)
        #print str(tmp)
        for it in tmp:
            r1=html.lstToUL(it,lambda x: html.a(x,'', "#"+x ))
            mnuConts.insertContents(r1)   
            #mnuConts.insertContents(html.itemToUlLi(it,lambda x: html.a(x,'', "#"+x ) ) ) 
        #mnuConts =html.incl('tmpls/tmpstatsnav.html')  
        ytml.mnuConts.insertContents(mnuConts)
        #return str(html.ul(ContentsLst[1:]) )
        #$% ytml.mnuConts.insertContents([html.a('Home','class=\"nm_cont_gl\"', '/geo/'+lng+'/home.html' ), html.a('Help','class=\"nm_cont_gl\"',  '/geo/'+lng+'/help.html' ) , html.ul(ContentsLst[1:]) ])   
        nm_sidebar_r1=ytml.MainRow[1].insertContents(html.span('', 'id=\"nm_sidebar_r1\" class=\"nm-lev-02\"')  )  
         
        nm_sidebar_r1CP=html.div([html.span('=','class=\"nm_sync\" title="Synchronize with Map"') , html.span('','class=\"nm_arrow nm_ar_l\" title="Move Left"' ),html.span('&nbsp','class=\"nm_play" title="Play Or Pause"'), html.span('','class=\"nm_arrow nm_ar_r\" title="Move Right"'), html.span('','class=\"pnrm_sp_txt\"'),  html.span(), html.span() ], 'id=\"pnrm_sp_cp\"')
        nm_pnrm= html.div('', 'id=\"nm_pnrm\"') 
        nm_pnrm.insertContents(html.div('', 'id=\"pnrm_SP\"'))
        nm_pnrm.insertContents(nm_sidebar_r1CP)
        ## nm_pnrm.insertContents(html.div(html.div('', 'id=\"pnrm_DC\" class=\"pnrm_DC_cls\"'), 'id=\"pnrm_BP\" class=\"pnrm_BP_cls\"'))  
        nm_pnrm.insertContents(html.div(html.div('', 'class=\"pnrm_DC_cls\"'), 'class=\"pnrm_BP_cls\"'))  
        nm_sidebar_r1_cont=html.rowCont("Photos", nm_pnrm , "nm_sidebar_r1_cont", 2) 
        nm_sidebar_r1_cont.attrAppendClass('nm-jsonly')  
        nm_sidebar_r1.insertContents(nm_sidebar_r1_cont) 
        ytml.MainRow[0][1].insertContents(html.div('', 'id=\"gmap_01\" class=\"nm_gmapv3\"'))
        ytml.MainRow[0][1].insertContents(html.div('', 'class=\"nm-dummy-last\"'))   
        ytml.html_head.insertContents(html.scriptSingleton ('pnrm_info',  rect= geotb.countryRect(cntr, 1), PhotoNum=[-1, 0, -1], NumOfSP =-1))
        ytml.html_head.insertContents(html.scriptSingleton ('gmaps_info', containers=['gmap_01'], rect= geotb.countryRect(cntr, 1))) 
        ytml.html_head.insertContents(html.scriptSingleton ('gener_info', cntr_ccTLD = cntrCodes[-1] ,cntr_cc= cntrCodes[0],  curLng=self.content_language, EnborderCountries =  geotb.EnBorderCountries(cntr), EnRegionsAndCities= geotb.EnRegionsAndCities(cntr), EnCapital= geotb.EnCapital(cntr)))    
        ##$ytml.html_head.insertContents(html.incl('tmpls/country.js'))  
        ytml.html_head.insertContents(html.script('google.load("language", "1")')) 
        ytml.html_head.insertContents(html.incl (tmplHead.render(self.tmplD)), 0)
        #ytml.html_head.insertContents(html.script ('', "/media/etc/country.js"))
        ytml.html_head.insertContents(html.script ('', "/media/js/appl.js"))
        ytml.html_head.insertContents(html.incl('tmpls/etc/applcommon.js'))
        ##ytml.html_head.insertContents(html.incl('tmpls/etc/ganalytics.js'))  
        #fl = open('/tmpl/basenm.html', 'r')  
        #fl = open('tmpls/country.js', 'r')  
        return ytml()          ##.replace('@(', '(').replace(')@', ')')  
      
def statsTbl(lng, arg, Qdict, Qqery, Qpath, ReqHandlInstance, argFooterStr='&nbsp' , tblLstHead=['N', 'Flag', 'Country']):
    """
       we sort only one field rest is ignored, sort_order has meaning only 'Desc' , Asc = default
       qdict is a self.request or a dictionary of the keyValues of query_string
    """    
    strOrder_by,  strNA =('order_by' , '')  
    def getReqQueryOrFalse(qKey, returnIfNotFound=False):
        rt=Qdict.get(qKey, returnIfNotFound)
        if rt != returnIfNotFound:rt =ReqHandlInstance.unescape(rt)  
        return rt
    geotbNotFullyLoaded = True   
    initInstance()     
    Qorder_by = getReqQueryOrFalse(strOrder_by)  
    Qchart = getReqQueryOrFalse('chart')
    Qchart = True if Qchart=='Yes' else False 
    Qccs=getReqQueryOrFalse('ccs')
    QInclEmpty=getReqQueryOrFalse('inclempty') 
    if Qccs:Qccs=Qccs.split(',') 
    Qorg=getReqQueryOrFalse('org') 
    if Qorder_by: 
        Qorder_byFld =Qorder_by.split('.')
        #print Qorder_byFld
        Qsort = Qorder_byFld[1] if len(Qorder_byFld)==2 else False
        Qorder_byFld= Qorder_byFld[0]   if Qorder_byFld[0] !='Country' else False 
    else:
        Qorder_byFld=False 
        Qsort=False    
    #Qchart_field = getReqQueryOrFalse('chart_field') 
    Qtop = unicode(Qdict.get('top', False))
    Qtop = int(Qtop) if Qtop.isnumeric() else False   
    
    def getVal(vl):
        return vl[lng] if isinstance(vl,(tbl.NMlngS, tbl.NMlng)) else vl 
    def ccInLst(cc, fldcode, val):
        tmp=geotb[cc].get(fldcode, False) 
        return False if tmp==False else val in tmp['en']      
    def getFieldsList (queryOrArgumentStr, autoLoadFields=True):
        FieldsLst = [ [ l[:1],l[1:] ] for l in     [ f.split('_') for f in queryOrArgumentStr.split('/')] ] 
        for fld in FieldsLst : 
            colKey=colKey=geotb.getColKeyByShortName(fld[0][0]) 
            if colKey is None: 
                return ReqHandlInstance.raiseErrCode400 ('No such Field:'+ fld[0][0])  
            fld[0].append(colKey) 
            ExistingSubFlds=geotb.Columns[colKey]['Fields']['en'][:] # [:]=copy otherwise we ovewrite the original 
            if len(fld[1])==0  and len(ExistingSubFlds) > 0: fld[1]=ExistingSubFlds
            for ix, subfield in enumerate (fld[1]):  
                if subfield not in ExistingSubFlds: 
                    return ReqHandlInstance.self.raiseErrCode400('%s %s %s %s' %('No such SubField:', subfield, 'available SubFields', str(ExistingSubFlds) )  )  
                else: 
                    # subfield=[subfield, ExistingSubFlds.index(subfield)] 
                    fld[1][ix]= [subfield ,  ExistingSubFlds.index(subfield)]
                    # now we have  [ [ [field,colkey] [ [subfield,subfieldIdx] ] ie [[['Capital', '&nbsp;.04.06'], [['name', 0], ['geographic coordinates', 1], ['time difference', 2], ['daylight saving time', 3]]], [['Independence', '&nbsp;.04.09'], []]]
            #if autoLoadFields:geotb.CSVload('res/geodump.csv', 2, skipValidations=True, colkey=colKey) 
        #if len(Fields) > 1 :geotb.CSVload('res/geodump.csv', 3, skipValidations=True)     maybe faster ?  
        return FieldsLst  
    if  geotbNotFullyLoaded : 
        geotb.CSVload('res/geodump.csv', 3, skipValidations=True) 
        geotbNotFullyLoaded=False 
    if arg.startswith('-'):
        colKey=colKey=geotb.getColKeyByShortName(arg)  
        tmp=[ geotb.Columns[it].getShortName() for it in  geotb.getColTree(colKey)[1]]
        FieldsArg='/'.join(tmp) #+'.html'  
    else:
        FieldsArg=arg     
    Fields=getFieldsList(FieldsArg) 
#    FieldsStr=''
#    for item in Fields:
#        if ir
#    return str(Fields)
    if Fields is None: return None
    rowKeys=geotb.keys() 
     
    if Qorg:rowKeys=[it  for it in rowKeys if ccInLst(it, '&nbsp;.04.07', Qorg)]
    if Qccs:rowKeys=[it  for it in Qccs if it in rowKeys]
    if Qorder_byFld:
        sortFields=getFieldsList(Qorder_byFld) 
        if sortFields is None: return None     
        for fld in sortFields: 
            valsLst=[  [  getVal (geotb[rk].get(fld[0][1], strNA) ),  rk] for rk in rowKeys]
            if len(fld[1]) != 0:
                valsLst=[ [vl[0] if vl[0]==strNA  else vl[0][fld[1][0][1]] ,  vl[1] ]            for vl in valsLst] 
    else:
        valsLst=[  [  geotb[rk]['&nbsp;']['country'][lng]  ,  rk] for rk in rowKeys] 
    valsLst.sort( reverse= (Qsort =='Desc') ) 
    rowKeys=[ vl[1] for vl in valsLst]                 
    
    #if Qtop: rowKeys=rowKeys[:Qtop] 
    
    tblLstRows=[] 
    #tmpLen=len(Fields)-1 
    cnt=1
    for rk in  rowKeys: 
        curCntr =  geotb[rk]['&nbsp;']['country'][lng]  
        curCntrCliped= utl.str_clip( curCntr ,  24)  
        cntrPath='/geo/' + lng +'/cc/'+ rk+'.html'
        curCntrTagA = html.a(curCntrCliped, href=cntrPath)
        curCntrTagA.attrSetTitle(curCntr) 
        curFlg=html.p( '', 'class=\"nm-flicon\"')
        curFlg.attrSetStyle("background-position: -" + str(geotb[rk]['&nbsp;']['flgof']*32) + "px")
        curFlg=html.a(curFlg, '', cntrPath)
        curFlg.attrSetTitle(curCntr)  
        curRowLst=['%3d' %(cnt), curFlg, curCntrTagA]
        incl=True
        for fld in Fields:  
            val=geotb[rk].get(fld[0][1], strNA)  
            if val==strNA and not (QInclEmpty):
                incl=False
                break
            if len(fld[1]) == 0:
                curRowLst.append(geotb._strGet(val , 'en' ))   
            else:  
                #curRowLst.extend ( [self.strNA if val is None else   geotb._strGet( val[ it[1] ] , 'en' )           for it in fld[1] ]  ) 
                val= [strNA if val ==strNA else    val[ it[1] ]     for it in fld[1] ]
                curRowLst.extend ( [geotb._strGet(it, 'en' ) for it in val ])
                #curRowLst.extend ( [self.strNA if val ==self.strNA else   geotb._strGet( val[ it[1] ] , 'en' )   for it in fld[1] ]  )  
        if isinstance(val, list) and len(val)==1:val=val[0]
        curRowLst.append( val if Qchart else '')      # extra last column
        if incl:
            cnt +=1
            tblLstRows.append (curRowLst)  
            if Qtop and cnt > Qtop:break 
    if Qchart:  
        LastColumn = geotb.Columns[Fields[-1][0][1]]
        QchartUnit=LastColumn.GetUnit()[lng] 
        if QchartUnit=='%':
            valueLst=[0, 100]   
        else :
            valueLst = [item[-1] for item in tblLstRows] 
            valueLst=utl.ut_itemise( valueLst,[],(float, int, long)) 
            #return str(valueLst)
            #valueLst= [item[-1] for item in tblLstRows if isinstance(item[-1],  (float, int, long))]  
        if len(valueLst) > 0: 
            ValueMax, ValueMin=(0, 0)
            ValueMax= max (valueLst)
            ValueMin= min (valueLst)
            ValueRange=float(ValueMax-ValueMin)  
        else:ValueRange=0    
        if ValueRange==0:
            Qchart=False
        else: 
            for item in tblLstRows:
                curVal= item[-1]            
                if isinstance(curVal,  (int, float, long) ): 
                    tmp=( (float(curVal)-ValueMin)/ValueRange) *100  
                    curGrp= html.p('&nbsp;', 'class=\"nm-graph\"') 
                    curGrp.attrSetStyle("%s%2.2f%s" %("width:",tmp,    "%")  )
                    item[-1]=curGrp 
                elif isinstance(curVal, list):  
                    curGrp= html.div('', 'class=\"nm-graph-lst\"')
                    for lstIdx, lstItem in enumerate (curVal):  
                        if isinstance(lstItem,  (int, float, long) ): 
                            tmp =   ( (lstItem-ValueMin)/ ValueRange) *100   
                        else:tmp=0    
                        curItem=html.span() if QchartUnit=='%' else html.div() 
                        #curItem.attrSetStyle("width:1px" if tmp==0 else "%s%2.2f%s" %("width:",tmp,    "%")  )
                        curItem.attrSetStyle("%s%2.2f%s" %("width:",tmp,    "%")  )
                        curItem.attrAppendCnt(lstIdx)
                        curGrp.insertContents(curItem)  
                    item[-1]=curGrp 
                    
    tblLstHeadSpan=['', '', '']
    
    linksList=['', '', 'Country']
    spanL=[] 
    tblTitle=[]
    fldStrLst=[]
    for ix, fld in enumerate (Fields):  
        colKey=fld[0][1]
        colCode=fld[0][0]
        Title=geotb.Columns[colKey].GetTitle()[lng]  
        tblTitle.append(Title)
        Unit=geotb.Columns[colKey].GetUnit()[lng] 
        Title_Unit = Title if Unit == '' else "%s%s(%s)" %(Title,'<br>',  Unit) 
        if len(fld[1]) == 0:    
            fldStrLst.append(Title) 
            tblLstHead.append(Title_Unit.replace(' ', '<br>') )  
            tblLstHeadSpan.append('') 
            linksList.append(colCode)
        else:  
            spanL.append([ix, len( fld[1]) ])  
            tblLstHeadSpan.append(Title_Unit)  
            subf=geotb.Columns[colKey]['Fields'][lng]  
            for sf in fld[1]:fldStrLst.append(Title + ' ' +  subf[sf[1]] )
            linksList.extend  ( [ colCode+'_'+subf[sf[1] ]           for sf in  fld[1] ]  )
            tblLstHead.extend ( [ subf[sf[1] ].replace(' ', '<br>')          for sf in  fld[1] ]  )    
    #map(lambda x: x.append(''), [ tblLstHeadSpan,tblLstHead, linksList] ) # extra last colume    
    linksList.append('')  # extra last colume  
    tblLstHeadSpan.append('(*) See Notes at bottom of the table')
    #tmp=html.a('[1] See Notes at bottom of the table', 'class=\"nm-anotation\"',  href='#cite_note1' )
    #tblLstHeadSpan.append(tmp)  
    tblTitle=', '.join(tblTitle)  
    tblLstHeadCntrl=['', '']   
    #return(str ( [Qqery,  self.strOrder_by,  Qqery.find(self.strOrder_by) > -1  ]) ) 
    NewQqery= Qqery if Qqery.find(strOrder_by) > -1 else Qqery + '&' + strOrder_by+'Asc' 
    reStr=r"order_by.*?(Asc|Desc)"
    tmpNF='rel=\"nofollow\"'  
    tmpOrderByPlus = strOrder_by + '='+ str(Qorder_by) 
    for it in  linksList[2:-1]: 
        tmpSrtValDn="%s%s%s%s" %(strOrder_by,"=",it,".Desc")
        tmpSrtValUp="%s%s%s%s" %(strOrder_by,"=",it,".Asc") 
        ReqNewDn=re.sub(reStr,tmpSrtValDn, NewQqery)
        ReqNewUp=re.sub(reStr,tmpSrtValUp, NewQqery) 
        LinkDn=html.span('&dArr;')  if tmpSrtValDn==tmpOrderByPlus else html.a('&darr;', tmpNF, Qpath+'?'+ReqNewDn)
        LinkUp=html.span('&uArr;') if tmpSrtValUp==tmpOrderByPlus else html.a('&uarr;' , tmpNF,  Qpath+'?'+ReqNewUp) 
        LinkUpDown=html.div([LinkUp, LinkDn], 'class=\"nm-updown\"') 
        tblLstHeadCntrl.append(LinkUpDown)
    tblLstHeadCntrl.append('')     
    if len( tblLstRows)==0 :tblLstRows= [ 'None'  for it in tblLstHead] #! otherwise we do not have col groups
    tblLstHead=[tblLstHeadSpan, tblLstHead, tblLstHeadCntrl ] 
    # caption=tblTitle '&nbsp'
    #argFooterStr
    #[html.a('* data source and acuracy please read:', href="/tos.html" ) ] 
    tblLstFoot=[  [argFooterStr], [', '.join(fldStrLst)] ]  
    tblContents=html.table(contentslst =tblLstRows, headerlst=  tblLstHead  ,footerlst=tblLstFoot,   attributes='',caption =  '&nbsp',    tagColums=True)    
    if len(tblLstRows) >0:
        tmp=len(tblLstRows[0] ) 
        ##print 'xxxxx '*10,  str( tblLstRows[0] ) 
        tblContents.foot[0][0].attrSet('colspan', str(tmp) ) 
        tblContents.foot[1][0].attrSet('colspan', str(tmp) )
    for ix, rk in enumerate (linksList):tblContents.tcolgroup[ix].attrAppendClass(rk) 
    tblContents.tcolgroup[-1].attrAppendClass('nm-last')
    if Qchart and len(Fields[-1][1]) > 1:  
        tmp= len(Fields[-1][1] )  * -1   
        for ix, it in enumerate (range(tmp-1, -1)):tblContents.head[-2][it+1].attrAppendClass('nm-chart-' + str (ix)) 
    for tmp in spanL :
        tblContents.head[0][tmp[0]+3].attrSet('colspan', str(tmp[1]))
        tblContents.head[0][tmp[0]+3].attrSetClass('nm-t-span') 
    tblContents.head[0][-1].attrSet('rowspan', str(len(tblContents.head.contents) -1  ))
    
    return tblContents   

class statsTblPageRQH (NMserver.ReqHadlerNM): 
    cookieName_Path=['geognosgeo','/geo/'] 
    isStaticContent=False
    useCashe = 4
    tmplHeader =   html.NMtmpl('tmpls/header_stats.html')   
    tmplFooter  =  html.incl  ('tmpls/tmpl_footer.html') 
    def cacheKey(self):return "%s?%s" %(self.request.path_info, self.request.query_string)  
    def getC(self, lng, operation, arg):
        def inclCountriesinResults():
            return [ cntr[1].contents.attrGetTitle()    for cntr in tblContents.body.contents]
        StatisticsDictCashe=getStatisticsDictCashe() 
        #print 'FFFFFF ' * 10 , str(StatisticsDictCashe) 
        #return  str (['ZZZZ ' * 10 , str(StatisticsDictCashe) ] )     
        Qenviron=self.request.environ   
        (argTitle, argDescription, argKeyWords)=('&nbsp', '&nbsp', '&nbsp')
        #argDescription= "%s %s%s" %(argTitle, 'colTitleXXXXXXXX', 'colFieldTitleXXXXXX')  
        argfrmOptions=''  
        if  operation =='countries-list-menu':
            argTitle=u'Countries list : '+arg   
            argKeyWords=argTitle + ',statistics,table,chart,largest,top,bottom' 
            argDescription=argTitle + ', statistics & charts'
            if   arg=='Latest': q=country_list.getLatest()
            elif arg=='All':    q=country_list.getAllSorted()
            elif arg=='Popular':q=country_list.getPopular()
            elif arg in StatisticsDictCashe.get('tagGroups', []):q=country_list.getAllWithTag(arg) 
            else: 
                self.raiseErrCode400(arg)
                return     
            tmp=[]
            #cite#  tmpDescr=html.ol() 
            for ix, item in enumerate(q):  
                #curAnotName= 'cite_note-'+str(ix+1)
                #curAnotatTxt="[%d]" %(ix+1) 
                #cite# tmp.append( html.span ([html.sup(html.a(curAnotatTxt,href='#'+curAnotName), 'class=\"nm-anotation\"' ),html.a(item.title, '', "../countries-list/%s%s" %(item.key().id_or_name(),'.html'), False, re.sub(r"\<.*?\>","&#x000A;",item.descr) ) ])    )   
                #title= 'International Organizations<br>' if item.flgs==2 else ''
                title ="%4d - %s " %(ix+1, item.title) 
                tmp.append(html.span (html.a(title, '', "../countries-list/%s%s" %(item.key().id_or_name(),'.html'),\
                           False, re.sub(r"\<.*?\>","&#x000A;",item.descr) ) )    ) 
                #cite#  aName=html.ol.li( item.descr) 
                #cite#  aName=html.ol.li("*%s  %s" %(curAnotatTxt, item.descr) )
                #cite# aName.attrSetName(curAnotName) 
                #cite# aName.attrSetId(curAnotName)
                #cite# tmpDescr.insertContents(aName )  
            #cite#  tblContents= html.div( [html.div(tmp, 'id=\"nm-tagcloud\"' ), html.div(tmpDescr, 'id=\"nm-tagdescr\"' )], 'id=\"nm-tagmenu\"') 
            tblContents= html.div( html.div(tmp, 'id=\"nm-tagcloud\"' ), 'id=\"nm-tagmenu\"')
        elif operation=='countries-list': 
            entity=country_list.get_by_key_name_eventual(arg) 
            if entity is None:
                self.raiseErrCode400(arg) 
                return
            else:    
                country_list.hitsIncrDefer(arg)
                req=entity.req_path
                reqSplit=req.split('?')
                reqArg=reqSplit[0].split('.html')[0]
                reqQS='' if len(reqSplit)==1 else reqSplit[1]
                userQS= Qenviron['QUERY_STRING'] 
                if userQS !='':reqQS = userQS
                reqDict= utl.dictFromQS(reqQS)  
                tblContents= statsTbl(lng, reqArg, reqDict, reqQS , self.request.environ['PATH_INFO'], self , entity.descr, tblLstHead=['N', 'Flag', 'Member Countries']) 
                if (self.response._Response__status[0]) ==400:return tblContents  
                argKeyWords='countries,list,statistics,table,Chart,' + tblContents.foot[1][0].contents  
                argTitle= re.sub(r"\<.*?>","",entity.title) 
                argDescription=re.sub(r"\<.*?>",". ",entity.descr) 
                tblContents= html.div(tblContents, 'id=\"nm_statscontainer\"') 
                
        elif operation=='countries':  
            #tblContents= html.div(statsTbl(lng, arg, self.request, Qenviron['QUERY_STRING'] , Qenviron['PATH_INFO'], self), 'id=\"nm_statscontainer\"') 
            tblContents= statsTbl(lng, arg, self.request, Qenviron['QUERY_STRING'] , Qenviron['PATH_INFO'], self)
            tmp=tblContents.foot[1][0].contents 
            #inclCountries= inclCountriesinResults()   
            argTitle='Countries list: '+  tmp 
            argKeyWords='Countries, Statistics, Table, List, Chart, Plot, '+tmp # tmp+": " +", ".join(inclCountries ) 
            argDescription= 'Table List and Statistics Chart of Countries '+ tmp
            tblContents= html.div(tblContents, 'id=\"nm_statscontainer\"') 
            if (self.response._Response__status[0]) ==400:return tblContents
        elif operation=='table': 
            return statsTbl(lng, arg, self.request, Qenviron['QUERY_STRING'] , Qenviron['PATH_INFO'], self)
            if (self.response._Response__status[0]) ==400:return tblContents
        ytml=html.y_html(html.y_html.width.doc3,html.y_html.sidebar.t2, html.incl('tmpls/etc/ga_async.js'))    
        urlcanonical=Qenviron['PATH_INFO']   
        #site = 'geognos ' 
        self.tmplD.update({'language':lng,'urlcanonical':urlcanonical, 'description':  argDescription ,'inclmap':False,'title':argTitle, 'keywords':argKeyWords, 'lang':lng, 'frmAction': "/geo/switch/", 'frm2Action':"/geo/switch/" , 'frmOptions':argfrmOptions, 'page_css':'geognos_bw'} )       
        
        ytml.setdefaults(argTitle, self.tmplFooter , '', sidebarR=ytml.ydivider.ge,  docclass= 'nm-'+ arg[0]+' nm-statistics')  
        ytml.cntr_panel.insertContents(html.incl(self.tmplHeader.render(self.tmplD)))  
        mnuConts= StdMenu(lng, False) 
        tmp="/geo/en/countries-list-menu/"
        for tag in StatisticsDictCashe.get('tagGroups', []):
            mnuConts.insertContents(html.ul.li( html.a(tag,  href=tmp+tag+'.html'))) 
        ytml.mnuConts.insertContents(mnuConts)  
        ytml.html_head.insertContents(html.incl (tmplHead.render(self.tmplD)))   
        ytml.html_head.insertContents(html.script ('', "/media/js/nmjsfwk00.js"))   
        ##ytml.html_head.insertContents(html.incl('tmpls/etc/statisticpages.js')) 
        ytml.MainRow[0].insertContents(tblContents) 
        return ytml()  

class NOPRQH(webapp.RequestHandler):
    def get(self): 
        initInstance() 
        self.response.out.write('OK')
class rootRQH(home_NotesRQH):
    def getC(self):   
        return home_NotesRQH.getC(self, 'en','home')
   
class cntr_lng_select(NMserver.ReqHadlerNM):  
    def getC(self,rest): 
        cntr_next = self.request.get("cntrCC") 
        lng_next =  self.request.get("lng_next") 
        rfr=self.request.referer
        if cntr_next != '':
            ##re.sub("//geo/", replaceStr, rfr,0)
            rfr=re.sub(r"geo\/(..)\/.*","geo/\\g<1>/cc/"+cntr_next+".html",rfr) 
        if lng_next != '':    
            rfr=re.sub(r"(\/geo\/)(..)(\/.*)","\\g<1>"+lng_next+"\\g<3>",rfr) 
        self.redirect(rfr)  
 
 

application = webapp.WSGIApplication(
     [ 
      (r"/geo/(?P<lang>.*?)/cc/(?P<country>.*)\.html", countryRQH), 
      #(r"/geo/(?P<lang>.*?)/table/(?P<chapter>.*)\.html", statsTblRQH),
      #(r"/geo/(?P<lang>.*?)/(?P<operation>.*?)/(?P<arg1>.*?/)(?P<arg2>/*.*/*?)\.html", statsTblPageRQH),
      (r"/geo/(?P<lang>.*?)/(?P<operation>table|countries|countries-list|countries-list-menu)/(?P<arg1>.*?)\.html", statsTblPageRQH), 
      (r"/geo/(?P<lang>.*?)/(?P<info>.*)\.html", home_NotesRQH),  
      (r"/sitemap.xml", home_Sitemap), 
      #(r"/rss.xml", home_RSS), feeds/(en|gr)/(\.*?)/(\.?)\.xml 
      (r"/feeds/(?P<lang>.*?)/(?P<tp>.*?)/(?P<arg>.*?)/(?P<fname>.*?)\.xml", feeds),
      
      #/feeds/en/tp/ggg.xml /feeds/en/typos/argum.xml
      (r"/geo/switch/(.*)",  cntr_lng_select),
      ##(r"/geo/__/../(.*)",  lang_select),  
      (r"/_ah/warmup", NOPRQH), 
      (r"/NOP/", NOPRQH),
      (r"/", rootRQH ),  
      (r"/*", NOPRQH)],
      debug=False)
#print "ffff " * 10
def main(): 
    run_wsgi_app(application)
if __name__ == "__main__":
    main() 